package com.example.Controller;

import com.example.baseObj.AjaxResult;
import com.example.entity.Category;
import com.example.entity.Goods;
import com.example.entity.OrderDetail;
import com.example.entity.OrderInfo;
import com.example.enumclass.BuyWay;
import com.example.enumclass.PayWay;
import com.example.repository.CategoryRepository;
import com.example.repository.GoodsRepository;
import com.example.repository.OrderDetailRepository;
import com.example.repository.OrderInfoRepository;
import com.example.service.OrderService;
import com.example.utils.SystemUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParser;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * Created by hongbin on 17/3/6.
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    private static Logger logger = LoggerFactory.getLogger(OrderController.class);

    private static final Integer SIZE = 10;

    //购买方式
    private static final  Map<String,String> bmaps= getBuyWaymaps();
    //支付方式
    private static final  Map<String,String> pmaps= getPayWaymaps();

    /**
     *可将service层与DAO层分开。
     */

    @Autowired
    private OrderService orderService;

    @RequestMapping("/index")
    public ModelAndView index(ModelMap map, HttpServletRequest req){

        logger.info("进行查询操作");
        //由于前后台分页差1 查询的时候 要-1  返回去的时候+1
        Integer page = req.getParameter("page")==null?0:(Integer.parseInt(req.getParameter("page"))-1);
        Integer size = SIZE;
        Pageable pages = new PageRequest(page==null?0:page,size,new Sort(Sort.Direction.DESC,"id"));




        Page<OrderInfo> goodsPage = orderService.findAllOrderInfo(pages);

        List<OrderInfo> orderlists = goodsPage.getContent();
        Integer totals = goodsPage.getTotalPages();


        map.put("bmaps",bmaps);
        map.put("pmaps",pmaps);


        map.put("totals",totals);
        map.put("page",page+1);
        map.put("orderlists",orderlists);
        map.put("menu_code","mainorder");
        return new ModelAndView("order/index");
    }

    @RequestMapping("/add")
    public ModelAndView create(ModelMap map){

        /***
         * 这是分类
         */
        List<Category> categories = orderService.findAllCategory();
        map.put("categories",categories);

        /***
         * 这个是订单id
         */
        String orderid = SystemUtils.getUniqueOrderid();
        map.put("orderid",orderid);

        logger.info("进行新增操作");
        return new ModelAndView("order/add");
    }

    @RequestMapping("/getGoodsByCid")
    public AjaxResult getGoodsByCid(@RequestParam String cid){

        logger.info("分类查询ID---"+cid);
        List<Goods> goods = orderService.getGoodsByCid(cid);

        return new AjaxResult(goods);

    }

    @RequestMapping("/save")
    public String save(OrderInfo orderInfo,@RequestParam(value = "orderDetailJson") String orderDetailJson){


        orderInfo.setCreatedate(new Date());
        OrderInfo order = orderService.saveOrderInfo(orderInfo);
        Gson gson = new Gson();
        List<OrderDetail> os = gson.fromJson(orderDetailJson,new TypeToken<List<OrderDetail>>() {}.getType());

        /**删除所有的子类*/
        orderService.deleteAllDetails(order);


        for (OrderDetail o : os){
            o.setOrderid(orderInfo.getOrderid());
            o.setOrderInfo(order);
            orderService.saveOrderDetail(o);
        }


        return  "1";
    }

    @RequestMapping(value = "/delete/{id}",method = RequestMethod.GET)
    public String delete(@PathVariable Long id){

        if (StringUtils.isEmpty(id)){
            return "0";
        }
        orderService.deleteOrderInfoById(id);
        logger.info("删除->id : "+id);

        return "1";
    }

    @RequestMapping(value = "/deleteAll",method = RequestMethod.POST)
    public String deleteAll(HttpServletRequest req){

        String ids = req.getParameter("ids");
        if(!StringUtils.isEmpty(ids)){
            String idList[] = ids.split("-");
            for (int i = 0; i < idList.length; i++) {
                Long id = Long.valueOf(idList[i]);

                orderService.deleteOrderInfoById(id);
            }
            return "1";
        }else{
            return "0";
        }
    }


    @RequestMapping(value = "/edit/{id}")
    public ModelAndView edit(@PathVariable Long id,ModelMap map){


        OrderInfo orderInfo = orderService.findOrderInfoById(id);

        List<Category> categories = orderService.findAllCategory();

        map.put("categories",categories);

        map.put("o",orderInfo);
        map.put("bmaps",bmaps);
        map.put("pmaps",pmaps);

        /**可以解决JSON循环问题。*/
        Set<OrderDetail> orderDetails  = orderInfo.getDetails();
        for (OrderDetail od : orderDetails){
            od.setOrderInfo(null);
        }
        Gson gson = new Gson();

        map.put("orderDetails_json",gson.toJson(orderDetails));
        map.put("orderDetails",orderDetails);
        logger.info("编辑->orderInfo : "+orderInfo.toString());
        logger.info("编辑->orderDetails : "+gson.toJson(orderDetails));



        return new ModelAndView("order/edit");
    }

    @RequestMapping("/get/{id}")
    public AjaxResult findOne(@PathVariable Long id){

        return new AjaxResult(orderService.findGoodsById(id));
    }


    @RequestMapping(value = "/show/{id}")
    public ModelAndView show(@PathVariable Long id,ModelMap map){


        OrderInfo orderInfo = orderService.findOrderInfoById(id);


        List<Category> categories = orderService.findAllCategory();

        /**产品分类*/
        Map<Long,String> cmaps = new HashMap<Long,String>();
        for (Category c : categories){
            cmaps.put(c.getId(),c.getName());
        }

        map.put("cmaps",cmaps);
        map.put("bmaps",bmaps);
        map.put("pmaps",pmaps);


        logger.info("bmaps-------"+bmaps);
        logger.info("pmaps-------"+pmaps);


        map.put("o",orderInfo);
        map.put("orderDetails",orderInfo.getDetails());



        return new ModelAndView("order/show");
    }


    //获取购买方式
    private static Map<String,String> getBuyWaymaps(){
        Map<String,String> bmaps = new HashMap<String,String>();
        bmaps.put("1",BuyWay.getName(1));
        bmaps.put("2",BuyWay.getName(2));
        return bmaps;
    }
    //获取支付方式
    private static Map<String,String> getPayWaymaps(){
        Map<String,String> pmaps = new HashMap<String,String>();
        pmaps.put("1", PayWay.getName(1));
        pmaps.put("2", PayWay.getName(2));
        pmaps.put("3", PayWay.getName(3));
        return pmaps;
    }
    //获取产品分类
    private  Map<Long,String> getCategoryMaps(){
        Map<Long,String> cmaps = new HashMap<Long,String>();
        List<Category> categories = orderService.findAllCategory();

        for (Category c : categories){
            cmaps.put(c.getId(),c.getName());
        }
        return cmaps;
    }
}
